package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.data.ItemSuggestion;
import org.aplikator.client.shared.data.Record;
import org.aplikator.client.shared.descriptor.FunctionDTO;
import org.jboss.errai.marshalling.client.api.Marshaller;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

@ClientMarshaller(ItemSuggestion.class)
@ServerMarshaller(ItemSuggestion.class)
public class ItemSuggestionMarshaller extends AbstractNullableMarshaller<ItemSuggestion> {

	/*@Override
	public Class<ItemSuggestion> getTypeHandled() {
		return ItemSuggestion.class;
	}*/

	@Override
	public ItemSuggestion[] getEmptyArray() {
		return new ItemSuggestion[0];
	}

	@Override
	public ItemSuggestion doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			EJObject eObj = o.isObject();
			String sugg = eObj.get("suggestion").isString().stringValue();
			int id = eObj.get("id").isNumber().intValue();
			String replacement = eObj.get("replacement").isString().stringValue();

			Marshaller<Object> recMarsh = ctx.getMarshallerInstance(Record.class.getName());
			Record record = (Record)recMarsh.demarshall(eObj.get("record"), ctx);
			
			ItemSuggestion iSugg = new ItemSuggestion(sugg, id, replacement, record);
			return iSugg;
		} else return null;
	}

	@Override
	public String doNotNullMarshall(ItemSuggestion o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder("{");
		MarshallingUtils.string("suggestion", o.getDisplayString(), builder).append(',');
		MarshallingUtils.number("id", o.getId(), builder).append(',');
		MarshallingUtils.string("replacement", o.getReplacementString(), builder).append(',');
		
		Marshaller<Object> recMarsh = ctx.getMarshallerInstance(Record.class.getName());
		MarshallingUtils.key("record", builder).append(':');
		builder.append(recMarsh.marshall(o.getRecord(), ctx));
		
		builder.append("}");
		return builder.toString();
	}
	
}
